#include <fpdf_doc.h>
#include <stdio.h>

#include "libs.h"

static struct toc_link list_head;

void printf_page_num(FILE* fp, FPDF_DOCUMENT doc, int page_num)
{
	char* buf;
	int len;

	buf = pdflib_page_text(doc, page_num, &len);
	if (buf) {
		printf("page %d content is: \n", page_num);
		printf_utf8(buf);
		printf("\n");

		reformat_text(fp, buf);
		free(buf);
	}
}

FPDF_DOCUMENT gdoc = NULL;
int main(int argc, char const *argv[]) 
{
	const char* test_doc = "test_doc.pdf";
	if (argc >= 2) {
		test_doc = argv[1];
	}
	printf("test_doc: %s\n", test_doc);
	FILE* fp = NULL;

	pdflib_init();
	FPDF_DOCUMENT doc = pdflib_open_doc(test_doc);
	gdoc = doc;
	if (!doc)
		goto EXIT;

	printf("Load pdf docs successful \n");
	int page_count = FPDF_GetPageCount(doc);
	printf("total %d pages\n\n", page_count);
	init_list(&list_head, page_count);

	char fname[256];
	char out_name[256];
	get_filename((char*)test_doc, fname);
	sprintf(out_name, "%s.md", fname);

	fp = fopen(out_name, "w");
	if (!fp)
		goto EXIT;
	//get Table Of Content
	pdflib_toc(doc, NULL, 0, &list_head);

	//printf_page_num(fp, doc, 1);
	//output to markdown
	output_to_md(doc, fp, &list_head);
	destroy_list(&list_head);
	fclose(fp);

EXIT:
	if(doc)
		pdflib_close_doc(doc);
	pdflib_exit();
	return 0;
}
